# -*- coding: utf-8 -*-
import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests
from common.helper import Helper
from urllib.parse import urlencode
from threading import Thread


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "华贵易出行交通工具意外伤害保险"
        self.queue = Queue()

    # 生成产品数据
    def genProductInfo(self):
        plan = {
            "days": ["1d", "7d", "30d", "1y"],
            "year": ["18-65"],
            "people_count": ["1"],
            "train_death": ["0", "100000", "200000", "500000"],
            "airplane_death": ["0", "1000000", "2000000", "5000000"],
            "ship_death": ["0", "100000", "200000", "500000"],
            "subway_death": ["0", "100000", "200000", "500000"],
            "bus_death": ["0", "100000", "200000", "500000"],
            "private_death": ["0", "50000", "100000", "200000"],
            "myselfDriver": ["0", "50000", "100000", "200000"],
        }
        # 生成队列
        for v in product(plan["days"], plan["year"], plan["people_count"], plan["train_death"], plan["airplane_death"],
                         plan["ship_death"], plan["subway_death"], plan["bus_death"], plan["private_death"],
                         plan["myselfDriver"]):
            data = Helper.formatProductInfo(plan, v)
            self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(**data))
            self.mysql._conn.commit()
            print(domain[self.name]["insert_sql"].format(**data))

    # 执行爬虫
    def requestJson(self, dt=None, mysql=None):

        refs = {
            "train_death": "056601003J04001",
            "airplane_death": "056601003J04002",
            "ship_death": "056601003J04003",
            "subway_death": "056601003J04004",
            "bus_death": "056601003J04005",
            "private_death": "056601003J04006",
            "myselfDriver": "056601003J04007",
        }
        duties = []
        for x in refs:
            duties.append( refs[x] + '-' + dt[x])
        duty = ','.join( duties )

        params = '''
        B0000000000000000287_Plan: planC
        B0000000000000000284_TextAge: 18Y-65Y
        B0000000000000000285_Period: 1D
        RiskCode: 056601003
        complicatedFlag: Y
        duty:056601003J04001-300000,056601003J04002-1000000,056601003J04003-100000,056601003J04004-0,056601003J04005-100000,056601003J04006-50000,056601003J04007-150000
        '''
        data = Helper.perfectJson(params)
        data["B0000000000000000285_Period"] =  dt["days"].upper() if dt["days"] !="30d" else "1M"
        data["duty"] = duty
        payload = urlencode(data).replace("+", "")
        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)
        if r.status_code == 200 and "productPrem" in r.text:
            price = r.json()["productPrem"]
            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price,
            }
            print( data )
            mysql.updatePrice( data )
        else:
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3,

            }
            mysql.updateTask( data )
            print("\n/*产品价格信息更新失败:%d/*"%dt["id"])
    def startProcess( self ):
        threads = []
        for i in range( 10 ):
            mysql = MysqlClient()
            t = Thread( target=Helper.runProcess,args=(mysql,self.name,self.requestJson))
            t.start()
            threads.append( t )
        for t in threads:
            t.join()
